/*
 * @Author: your name
 * @Date: 2024-04-22 12:00:58
 * @LastEditTime: 2024-04-22 13:31:28
 * @LastEditors: your name
 * @Description: In User Settings Edit
 * @FilePath: \.leetcode\110.平衡二叉树.cpp
 */
/*
 * @lc app=leetcode.cn id=110 lang=cpp
 *
 * [110] 平衡二叉树
 */

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int getHeight(TreeNode* root){
        if(!root){
            return 0;
        }
        int left = getHeight(root->left);
        if(left == -1) return -1;
        int right = getHeight(root->right);
        if(right == -1) return -1;
        // 高度差大于1
        if(abs(left-right) > 1){
            return -1;
        }else{
            return 1+max(left,right);// 以当前节点为根节点的树的最大高度。
        }

    }
    bool isBalanced(TreeNode* root) {
        int res = getHeight(root);
        return res == -1 ? false:true;
    }
};
// @lc code=end

